package edu.ustb.service.user.Impl;

import edu.ustb.domain.user.UserAddress;
import edu.ustb.domain.user.Users;
import edu.ustb.mapper.user.UserAddressDao;
import edu.ustb.mapper.user.UsersDao;
import edu.ustb.service.user.UsersService;
import edu.ustb.utils.MybatisUtil;

import java.util.List;

public class UsersServiceImpl implements UsersService {

    private UsersDao usersDao = MybatisUtil.getMapper(UsersDao.class);

    @Override
    public List<Users> findAll() {
        List<Users> usersList = usersDao.findAll();
        for (Users users : usersList) {
            System.out.println(users);
        }
        if (usersList.size() != 0) {
            MybatisUtil.commit();
            MybatisUtil.close();
            return usersList;
        } else {
            MybatisUtil.rollBack();
            return null;
        }
    }

    @Override
    public Users login(String ident, String passWord) {
        Users users;
        if(ident.indexOf('@')!=-1)
        {
            users = usersDao.findByEmail(ident);
        }
        else
        {
            users = usersDao.findByPhoneNum(ident);
        }
        System.out.println(users);
        if(users.getUserPass().equals(passWord))
        {
            return users;
        }
        else {
            return null;
        }
    }

    @Override
    public int register(Users users) {
        UsersDao usersDao = MybatisUtil.getMapper(UsersDao.class);
        if(usersDao.findByPhoneNum(users.getUserPhone())!=null)
        {
            return 2;
        }
        if(usersDao.add(users)>0)
        {
            MybatisUtil.commit();
            return 1;
        }
        else
        {
            return 0;
        }
    }

    @Override
    public List<UserAddress> findAddress(String userPhone) {
        UserAddressDao userAddressDao = MybatisUtil.getMapper(UserAddressDao.class);
        List<UserAddress> userAddressList = userAddressDao.findAddress(userPhone);
        for (UserAddress users : userAddressList) {
            System.out.println(users);
        }
        MybatisUtil.close();
        return userAddressList;
    }

    @Override
    public boolean insert(UserAddress address) {
        UserAddressDao userAddressDao = MybatisUtil.getMapper(UserAddressDao.class);
        int flag = userAddressDao.insert(address);
        System.out.println("查找");
        MybatisUtil.commit();
        if(flag>0)
        {
            MybatisUtil.close();
            return true;
        }
        else
        {
            MybatisUtil.rollBack();
            MybatisUtil.close();
            return false;
        }
    }
}
